<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<span>管理员编辑</span>
		</div>
		<el-form :model="edit_form" :rules="rules" ref="edit_form" label-width="100px">
			<el-form-item label="用户名" prop="username">
				<el-input v-model="edit_form.username" disabled></el-input>
			</el-form-item>
			<el-form-item label="姓名" prop="fullname">
				<el-input v-model="edit_form.fullname"></el-input>
			</el-form-item>
			<el-form-item label="角色" prop="role_id">
				<el-select v-model="edit_form.role_id" placeholder="请选择" :disabled="$route.params.user_id == 1">
					<el-option v-for="item in role_options" :key="item.role_id" :label="item.role_name"
						:value="item.role_id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="性别" prop="sex">
				<el-radio-group v-model="edit_form.sex">
					<el-radio label="男"></el-radio>
					<el-radio label="女"></el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="手机号" prop="tel">
				<el-input v-model="edit_form.tel"></el-input>
			</el-form-item>
			<el-form-item label="邮箱" prop="email">
				<el-input v-model="edit_form.email"></el-input>
			</el-form-item>
			<el-form-item label="头像">
				<!--v-bind让等号后面的生效 show-file-list="false"中的false是字符串 :show-file-list="false"中的false是布尔值 -->
				<el-upload class="avatar-uploader" action="`${$server}/upload/common/`" :show-file-list="false"
					accept="image/*" :before-upload="beforeAvatarUpload" :on-error="handleUpeloadError" :headers="headers"
					:data="{ type: 'avatar' }" :on-success="handleUploadSuccess">
					<img v-if="edit_form.avatar" :src="edit_form.avatar" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleEdit">保存修改</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
import { Admin, Role } from "@/api";
export default {
	name: 'Edit',
	data() {
		return {
			edit_form: {
				user_id: '',
				username: '',
				fullname: '',
				role_id: '',
				sex: '',
				tel: '',
				email: '',
				role_name: '',
				avatar: '',
			},
			role_options: [],
			headers: { Authorization: `Bearer ${sessionStorage.access_token}` },
			rules: {
				username: [{ required: true, message: "请填写用户名！", trigger: 'blur' }],
				fullname: [{ required: true, message: "请填写姓名！", trigger: 'blur' }],
				tel: [
					{ required: true, message: "请填写姓名！", trigger: 'blur' },
					{
						pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
						message: '请填写合规的手机号！',
						trigger: 'blur'
					}
				],
				email: [
					{ required: true, message: "请填写姓名！", trigger: 'blur' },
					{
						pattern: /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/,
						message: '请填写合规的网址！',
						trigger: 'blur'
					}
				],
				avatar: [{ required: true, message: "请上传头像！", trigger: 'blur' },],
			}
		}
	},
	// 页面一打开就要获取地址栏的参数
	mounted() {
		// 获取地址栏参数
		let { user_id } = this.$route.params;
		// console.log(user_id);
		this.init(user_id);
	},
	/* beforeDestroy() {
		console.log('beforeDestroy');
	},
	beforeRouteLeave(to, from, next) {
		console.log('beforeRouteLeave');
		next();
	},*/

	// 组件内的守卫：路由地址更新
	beforeRouteUpdate(to, from, next) {
		let { user_id } = to.params;
		next();
		this.init(user_id);
	},
	methods: {
		// 初始化：通过async函数保证Ajax顺序执行
		async init(user_id) {
			// 加载角色列表，起别名
			let { status: role_status, data: roles } = await Role.list();
			if (role_status) {
				this.role_options = roles;
			}
			// 加载管理员资料
			let { status, data } = await Admin.info({ user_id });
			if (status) {
				// 还原表单
				this.edit_form = data;
			}
		},

		// 上传之前的检查
		// file 文件对象，里面包含文件的信息：类型、名字、大小
		beforeAvatarUpload(file) {
			console.log(file);
			let reg = /^image\/(jpeg||png)$/;
			const isImage = reg.test(file.type);
			const isLt2M = file.size / 1024 / 1024 < 2;

			if (!isImage) {
				this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!');
			}
			return isImage && isLt2M;
		},
		// 上传失败的函数：判断是否是正方形，且大小不超过2MB
		handleUpeloadError(err, file, fileList) {
			// ES6起别名
			let { status, message } = err;
			switch (status) {
				case 400:
					// 先将字符串转为对象，然后对象解构
					let { status, msg } = JSON.parse(message);
					// 信息提示
					this.$message.error(msg);
					break;
				case 401:
					let { code } = JSON.parse(message);
					this.$message.error(`错误代码：401，${code},请重新登录！`);
					break;
				default:
					break;
			}


		},
		// 上传成功，显示在页面上
		handleUploadSuccess(res, file) {
			// 临时内存地址 ，用于预览头像
			// this.imageUrl = URL.createObjectURL(file.raw);

			let { status, msg, src } = res;
			if (status) {
				// 预览头像:用返回的图片地址
				this.edit_form.avatar = src;
				// 信息提示
				this.$message.success(msg);
			}
		},
		async handleEdit() {
			// 表单验证
			this.$refs.edit_form.validate(async (valid) => {
				if (valid) {
					let { status, msg } = await Admin.edit(this.edit_form);
					if (status) {
						this.$message.success(msg);
						this.$router.push('/system/admin/list');
					} else {
						this.$message.error(msg);
					}
				}
			});
		},
	},
}
</script>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409EFF;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
